﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Supplier;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using BasicInformation.Infrastructure.Interface;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Supplier
{
    /// <summary>
    /// 供应商管理添加处理类
    /// </summary>
    public class AddSupplierHandler : IRequestHandler<AddSupplierCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly IMapper mapper;
        private readonly ILogger<AddSupplierHandler> logger;

        public AddSupplierHandler(DatabaseContext db,IMapper mapper,ILogger<AddSupplierHandler> logger)
        {
            this.db = db;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(AddSupplierCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var supplier = mapper.Map<SupplierModel>(request);
            var model = db.SqlSugar.Queryable<SupplierModel>().Where(x => x.SupplierCode == request.SupplierCode&&x.SupplierName==request.SupplierName).Count();
            if (model > 0)
            {
                result.Msg = "供应商管理已存在，请重新输入";
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
                return await Task.FromResult(result);
            }
            int r =  await db.SqlSugar.Insertable(supplier).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "供应商管理添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "供应商管理添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
